import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


public class SteamXMLParsers
{
	private static final String API_KEY="2E0E6C2154C0346B66C4E9099DDFE423";
	private static final String USER_SUMMARY="http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=";
	private static final String FRIENDS_LIST="http://api.steampowered.com/ISteamUser/GetFriendList/v0001/?key=";
	private static final String RECENTLY_PLAYED="http://api.steampowered.com/IPlayerService/GetRecentlyPlayedGames/v0001/?key=";
	private static final String FORMAT="&format=xml";
	
	public static String returnXML(String profileURL)
	{
		String data=null;
		
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_AUTHENTICATION, false);
            HttpGet request = new HttpGet(profileURL);
            HttpResponse response = httpClient.execute(request);

            Integer statusCode = response.getStatusLine().getStatusCode();
            if(!statusCode.toString().startsWith("20")) {
                if(statusCode == 401) {
                    throw new Exception("UNAUTHORIZED");
                }

                throw new Exception("HTTP_ERROR");
            }

            data = EntityUtils.toString(response.getEntity());
            httpClient.close();
        }
        catch(Exception e)
        { 
        	System.out.println("System Error during pull");
        }
        
        return data;
	}
	
	public static String createUserSummaryURL(SteamUser user)
	{
		String userSummaryURL = USER_SUMMARY+API_KEY+"&steamids="+user.getSteamID()+FORMAT;
		return userSummaryURL;
	}
	
	public static String createUserSummaryURL(String steamFriendID)
	{
		String userSummaryURL = USER_SUMMARY+API_KEY+"&steamids="+steamFriendID+FORMAT;
		return userSummaryURL;
	}
	
	public static String createFriendsListURL(SteamUser user)
	{
		String friendsURL = FRIENDS_LIST+API_KEY+"&steamid="+user.getSteamID()+"&relationship=friend"+FORMAT;
		return friendsURL;
	}
	
	public static String createRecentlyPlayedURL(SteamUser user)
	{
		String friendsURL = RECENTLY_PLAYED+API_KEY+"&steamid="+user.getSteamID()+FORMAT;
		return friendsURL;
	}
	
	public static Document parseXML(String userXML) throws SAXException, IOException, ParserConfigurationException
	{
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(userXML));
        Document doc = dBuilder.parse(is);
        return doc;
	}
	 
	public static String getCharacterDataFromElement(Element e) 
	{
		    Node child = e.getFirstChild();
		    if (child instanceof CharacterData) 
		    {
		       CharacterData cd = (CharacterData) child;
		       return cd.getData();
		    }
		    return "?";
	}

	public void printUserSummary(String userSummary)
	{
		String userSummaryXML = returnXML(userSummary);
		System.out.println("User Summary: ");
		System.out.println(userSummaryXML);
	}
	
	public void friendsList(String friendsListURL)
	{
		String friendsListXML = returnXML(friendsListURL);
		System.out.println("Friends List: ");
		System.out.println(friendsListXML);
	}
	
	public void recentlyPlayed(String recentlyPlayedURL)
	{
		String recentlyPlayedXML = returnXML(recentlyPlayedURL);
		System.out.println("Recently Played Games: ");
		System.out.println(recentlyPlayedXML);
	}
	
	public static SteamUser[] friendsListParse(String xmlResults)
	{
		
		Document friendList = null;
		try
		{
			friendList = parseXML(xmlResults);
		}
		catch (SAXException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (ParserConfigurationException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		NodeList friendNodes = friendList.getElementsByTagName("friend");
		
		String[] steamID = new String[friendNodes.getLength()];
		for(int i=0;i<friendNodes.getLength();i++)
		{
			Element element = (Element)friendNodes.item(i);
			NodeList sIDElement = element.getElementsByTagName("steamid"); 
			Element line = (Element) sIDElement.item(0);
			steamID[i] = getCharacterDataFromElement(line);
			System.out.println("Current SteamID: "+steamID[i]);
		}
		
		SteamUser[] friendsAndAvatars = new SteamUser[steamID.length];
		
		System.out.println("steamID Length: "+steamID.length);
		
		for(int j=0; j<steamID.length;j++)
		{
			String userSummaryURL = createUserSummaryURL(steamID[j]);
			String xml = returnXML(userSummaryURL);
			
			System.out.println("player XML: "+xml);
			
			Document playerList = null;
			try
			{
				playerList = parseXML(xml);
				System.out.println("After Parse of XML");
			}
			catch (SAXException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch (ParserConfigurationException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			NodeList playerNodes = playerList.getElementsByTagName("player");
			System.out.println("PlayerNodes Count: "+playerNodes.getLength());

			Element element = (Element)playerNodes.item(0);
			System.out.println("Element: "+element.getTextContent());
			
			NodeList userElement = element.getElementsByTagName("personaname"); 
			Element line = (Element) userElement.item(0);
			friendsAndAvatars[j] = new SteamUser();
			friendsAndAvatars[j].setHandle(line.getTextContent());
				
			userElement = element.getElementsByTagName("avatarmedium"); 
			line = (Element) userElement.item(0);
			friendsAndAvatars[j].setAvatar(line.getTextContent());
			
			userElement = element.getElementsByTagName("personastate");
			line = (Element) userElement.item(0);
			friendsAndAvatars[j].setStatus(Integer.parseInt(line.getTextContent()));
		}
		
		return friendsAndAvatars;
	}
		
}

